<template>
  <dark-mode-container
    flex
    h-full
    :inverted="themeStore.sider.inverted"
    @mouseleave="resetFirstDegreeMenus"
  >
    <div flex-1-hidden flex-col-stretch h-full>
      <global-logo
        :show-title="false"
        :style="{ height: themeStore.header.height + 'px' }"
      />
      <n-scrollbar flex-1-hidden>
        <mix-menu-detail
          v-for="item in firstDegreeMenus"
          :key="item.key"
          :item-key="item.key"
          :active-key="activeParentKey"
          :label="item.label"
          :icon="item.icon"
          :is-mini="appStore.siderCollapse"
          @click="handleMixMenu(item.key, item.path, item.hasChildren)"
        />
      </n-scrollbar>
      <mix-menu-collapse />
    </div>
    <mix-menu-drawer :visible="drawerVisible" :menus="activeChildMenus" />
  </dark-mode-container>
</template>

<script setup lang="ts">
import { useAppStore, useRouteStore, useThemeStore } from "@/store";
import { useBoolean } from "@/hooks";
import { GlobalLogo } from "@/layouts/common";
import { MixMenuCollapse, MixMenuDetail, MixMenuDrawer } from "./components";

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const themeStore = useThemeStore();
const routeStore = useRouteStore();
const {
  bool: drawerVisible,
  setTrue: openDrawer,
  setFalse: hideDrawer,
} = useBoolean();

const activeParentKey = ref("");

const firstDegreeMenus = computed(() =>
  routeStore.menus.map((item) => {
    const { key, path, label } = item;
    const icon = item?.icon;
    const hasChildren = Boolean(item.children && item.children.length);

    return {
      key,
      label,
      path,
      icon,
      hasChildren,
    };
  })
);

function getActiveParentRouteName() {
  firstDegreeMenus.value.some((item) => {
    const flag = (route.name as string)?.includes(item.key);
    if (flag) {
      activeParentKey.value = item.key;
    }
    return flag;
  });
}

function handleMixMenu(key: string, path: string, hasChildren: boolean) {
  console.log(key, path, hasChildren);
  activeParentKey.value = key;
  if (hasChildren) {
    openDrawer();
  } else {
    router.push(path);
  }
}

function resetFirstDegreeMenus() {
  getActiveParentRouteName();
  hideDrawer();
}

const activeChildMenus = computed(() => {
  const menus: App.GlobalMenuOption[] = [];
  routeStore.menus.some((item) => {
    const flag = item.key === activeParentKey.value && !!item.children?.length;
    if (flag) {
      menus.push(...(item.children || []));
    }
    return flag;
  });
  return menus;
});

watch(
  () => route.name,
  () => getActiveParentRouteName(),
  { immediate: true }
);
</script>

<style scoped></style>
